<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2021/03/01
 * Time: 10:10AM
 */
namespace App\Api\Controllers\QfPay;

use App\Api\Controllers\BaseController;
use App\Common\PaySuccessAction;
use App\Common\RefundSuccessAction;
use App\Models\MerchantWalletDetail;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\RefundOrder;
use App\Models\UserWalletDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class NotifyController extends BaseController
{
    //钱方 支付回调
    public function pay_notify_url(Request $request)
    {
        try {
            $data = $request->all();
            Log::info('钱方-支付回调');
            Log::info($data);

            if (isset($data['notify_type'])) { //通知类型:payment-支付;refund-退款;close-关闭
                if ($data['notify_type'] == 'payment') {
                    $trade_no = isset($data['syssn']) ? $data['syssn'] : ""; //交易流水号
                    $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : ''; //外部订单号,开发者定义订单号

                    $day = date('Ymd', time());
                    $table = 'orders_' . $day;
                    if (Schema::hasTable($table)) {
                        $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                    } else {
                        $order = Order::where('out_trade_no', $out_trade_no)->first();
                        if (!$order) {
                            $order = Order::where('trade_no', $trade_no)->first();
                        }
                    }

                    //订单存在
                    if ($order) {
                        $pay_type = isset($data['pay_type']) ? $data['pay_type'] : ''; //支付类型:支付宝扫码:800101； 支付宝反扫:800108；支付宝服务窗：800107；微信扫码:800201； 微信刷卡:800208； 微信公众号支付:800207
                        $txdtm = isset($data['txdtm']) ? $data['txdtm'] : ''; //请求交易时间
                        $txamt = isset($data['txamt']) ? $data['txamt'] : ''; //订单支付金额，单位分
                        $respcd = isset($data['respcd']) ? $data['respcd'] : ''; //交易返回码，默认返回所有订单状态的返回码
                        $sysdtm = isset($data['sysdtm']) ? $data['sysdtm'] : $txdtm; //系统交易时间
                        $paydtm = isset($data['paydtm']) ? $data['paydtm'] : ''; //用户支付时间
                        $cancel = isset($data['cancel']) ? $data['cancel'] : ''; //撤销/退款标记 正常交易：0；已撤销：2；已退货：3
                        $cardcd = isset($data['cardcd']) ? $data['cardcd'] : ''; //微信、支付宝的用户openid 参数
                        $goods_name = isset($data['goods_name']) ? $data['goods_name'] : ''; //商品名称或标示
                        $status = isset($data['status']) ? $data['status'] : ''; //交易状态码：1：支付成功
                        $txcurrcd = isset($data['txcurrcd']) ? $data['txcurrcd'] : ''; //币种：港币：HKD ；人民币：CNY
                        $mchid = isset($data['mchid']) ? $data['mchid'] : ''; //子商户号

                        $buyer_pay_amount = isset($data['txamt']) ? $data['txamt']/100 : $order->total_amount; //订单支付金额
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                        $fee_amount = ($order->rate * $buyer_pay_amount)/100;

                        //系统订单 等待支付
                        if ($order->pay_status == 2) {
                            $in_data = [
                                'status' => '1',
                                'pay_status' => 1,
                                'pay_status_desc' => '支付成功',
                                'trade_no' => $trade_no,
                                'pay_time' => $sysdtm,
                                'buyer_id' => $cardcd,
                                'buyer_pay_amount' => $buyer_pay_amount,
                                'receipt_amount' => $buyer_pay_amount,
                                'fee_amount' => $fee_amount
                            ];
                            $this->update_day_order($in_data, $out_trade_no);

                            if (strpos($out_trade_no, 'scan')) {

                            } else {
                                //支付成功后的动作
                                $data = [
                                    'ways_type' => $order->ways_type,
                                    'company' => $order->company,
                                    'ways_type_desc' => $order->ways_type_desc,
                                    'source_type' => '24000', //返佣来源
                                    'source_desc' => '钱方', //返佣来源说明
                                    'total_amount' => $order->total_amount,
                                    'out_trade_no' => $order->out_trade_no,
                                    'other_no' => $order->other_no,
                                    'rate' => $order->rate,
                                    'fee_amount' => $fee_amount,
                                    'merchant_id' => $order->merchant_id,
                                    'store_id' => $order->store_id,
                                    'user_id' => $order->user_id,
                                    'config_id' => $order->config_id,
                                    'store_name' => $order->store_name,
                                    'ways_source' => $order->ways_source,
                                    'pay_time' => $sysdtm,
                                    'device_id' => $order->device_id,
                                ];
                                PaySuccessAction::action($data);
                            }
                        }
                    }

                } elseif ($data['notify_type'] == 'refund') {
                    $trade_no = isset($data['orig_syssn']) ? $data['orig_syssn'] : ""; //交易流水号
                    $out_trade_no = isset($data['orig_out_trade_no']) ? $data['orig_out_trade_no'] : ''; //外部订单号,开发者定义订单号

                    $day = date('Ymd', time());
                    $table = 'orders_' . $day;
                    if (Schema::hasTable($table)) {
                        $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                    } else {
                        $order = Order::where('out_trade_no', $out_trade_no)->first();
                        if (!$order) {
                            $order = Order::where('trade_no', $trade_no)->first();
                        }
                    }

                    //订单存在
                    if ($order) {
                        $txamt = isset($data['txamt']) ? $data['txamt']: 0; //退款金额，单位分
                        $status = isset($data['status']) ? $data['status']: ''; //交易状态码：1-支付成功
                        $txdtm = isset($data['txdtm']) ? $data['txdtm']: ''; //请求交易时间
                        $sysdtm = isset($data['sysdtm']) ? $data['sysdtm']: $txdtm; //系统交易时间
                        $mchid = isset($data['mchid']) ? $data['mchid']: ''; //子商户号
                        $new_out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no']: ''; //
                        $syssn = isset($data['syssn']) ? $data['syssn']: ''; //钱方订单号
                        $respcd = isset($data['respcd']) ? $data['respcd']: ''; //请求下单结果返回码,0000表示成功

                        $buyer_pay_amount = number_format($txamt/100, 2, '.', '');
                        $fee_amount = $order->rate * $buyer_pay_amount;

                        //系统订单成功
                        if ($order->pay_status == 1) {
                            $fee_amount = max($order->fee_amount*100 - $fee_amount, 0); //剩余手续费，单位：分
                            $in_data = [
                                'status' => '6',
                                'pay_status' => 6,
                                'pay_status_desc' => '已退款',
                                'refund_no' => $trade_no,
                                'refund_amount' => $buyer_pay_amount,
                                'fee_amount' => $fee_amount/100
                            ];
                            $this->update_day_order($in_data, $out_trade_no);

                            RefundOrder::create([
                                'ways_source' => $order->ways_source,
                                'type' => $order->ways_type,
                                'refund_amount' => $txamt/100, //退款金额
                                'refund_no' => $syssn, //平台退款单号
                                'store_id' => $order->store_id,
                                'merchant_id' => $order->merchant_id,
                                'out_trade_no' => $out_trade_no,
                                'trade_no' => $order->trade_no
                            ]);

                            //退款成功后的操作
                            RefundSuccessAction::action([
                                'out_trade_no'=>$out_trade_no,
                                'refund_no' => $syssn
                            ]);
                        }
                    }
                }

            }

            return 'SUCCESS';
        } catch (\Exception $ex) {
            Log::info('钱方支付异步报错');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


}
